import { Injectable } from '@angular/core';
import { AppStoreModule } from './store';
import { Store, select } from '@ngrx/store';
import { getModalBox } from './modal-box.selector';
import { ModalBoxState, ModalBoxType } from './modal-box.reducer';
import { SetModalBoxType, SetModalBoxVisible } from './modal-box.action';
import { timer } from 'rxjs';

@Injectable({
    providedIn: AppStoreModule
})

export class BatchActionsService {
    private modalBoxState: ModalBoxState;

    constructor(private $store: Store<AppStoreModule>) {
        this.$store.pipe(select(getModalBox)).subscribe(modalBox => this.modalBoxState);
    }

    /**
     * 弹窗显示隐藏/类型
     */
    controlModalBox(visible = true, modalType?: ModalBoxType) {
        if (modalType) {
            this.$store.dispatch(SetModalBoxType({ modalType }));
        }
        this.$store.dispatch(SetModalBoxVisible({ visible }));
        if (!visible) {
            timer(500).subscribe(() => this.$store.dispatch(SetModalBoxType({ modalType: ModalBoxType.Default })));
        }
    }

    changeModalBox(modalType: ModalBoxType) {
        this.$store.dispatch(SetModalBoxType({ modalType }));
    }
}
